//server.cpp，服务端
#include <iostream>
#include <unordered_map>
#include <string>
#include <memory>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <mutex>
#pragma comment(lib, "Ws2_32.lib")

// 许可证结构体，包含序列号和当前使用人数
struct License
{
    int usageCount = 0;
    std::mutex usageMutex;

    // 默认构造函数
    License() = default;

    // 禁用拷贝构造函数和拷贝赋值操作符
    License(const License&) = delete;
    License& operator=(const License&) = delete;

    // 允许移动构造函数和移动赋值操作符
    License(License&&) = default;
    License& operator=(License&&) = default;
};

//全局许可证数据库，使用unordered_map存储序列号和对应的许可证指针
std::unordered_map<std::string, std::unique_ptr<License>> licenseDatabase;
const int MAX_USAGE = 5; //假设每个序列号最多允许5个并发使用

//检查序列号是否有效，并更新使用人数
bool validateLicense(const std::string& serialNumber, std::string& response)
{
    auto it = licenseDatabase.find(serialNumber);
    if (it == licenseDatabase.end())
    {
        response = "无效许可证。";
        return false;
    }

    std::lock_guard<std::mutex> lock(it->second->usageMutex);
    if (it->second->usageCount < MAX_USAGE)
    {
        it->second->usageCount++;
        response = "授权成功。";
        return true;
    }
    else
    {
        response = "许可证使用已达到上限。";
        return false;
    }
}
int main()
{
    // 初始化Winsock
    WSADATA wsadata;
    if (WSAStartup(MAKEWORD(2, 2), &wsadata) != 0)
    {
        std::cerr << "Winsock初始化失败。" << std::endl;
        return 1;
    }

    // 创建服务器socket
    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (serverSocket == INVALID_SOCKET)
    {
        std::cerr << "创建服务器socket失败。" << std::endl;
        WSACleanup();
        return 1;
    }

    //设置服务器地址和端口
    sockaddr_in serverAddr = {};
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr("192.168.156.29");//先使用ipconfig获得本机IP地址，放到这里
    serverAddr.sin_port = htons(55666);

    //绑定socket到地址和端口
    if (bind(serverSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
    {
        std::cerr << "绑定服务器socket失败。" << std::endl;
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    //开始监听连接
    if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR)
    {
        std::cerr << "监听失败。" << std::endl;
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }
    //随便设置一个有效许可证
    licenseDatabase["1234567890"] = std::make_unique<License>();
    licenseDatabase["0987654321"] = std::make_unique<License>();

    std::cout << "服务器已启动，等待客户端连接..." << std::endl;

    //接受客户端连接并处理请求
    while (true) {
        sockaddr_in clientAddr;
        int clientAddrSize = sizeof(clientAddr);
        SOCKET clientSocket = accept(serverSocket, (sockaddr*)&clientAddr, &clientAddrSize);
        if (clientSocket == INVALID_SOCKET)
        {
            std::cerr << "接受客户端连接失败" << std::endl;
            continue;
        }

        std::cout << "接收到客户端连接" << std::endl;

        //接收客户端发送的序列号
        char buffer[1024] = { 0 };
        int bytesRead = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
        if (bytesRead <= 0)
        {
            std::cerr << "接收序列号失败。" << std::endl;
            closesocket(clientSocket);
            continue;
        }

        std::string serialNumber(buffer, bytesRead);
        std::string response;

        //验证序列号
        bool isValid = validateLicense(serialNumber, response);

        //发送验证结果给客户端
        send(clientSocket, response.c_str(), response.size(), 0);

        //关闭客户端连接
        closesocket(clientSocket);
    }

    //关闭服务器socket并清理Winsock
    closesocket(serverSocket);
    WSACleanup();

    return 0;
}